//
//  libControlScrollView.m
//  lib
//
//  Created by yappa on 10/04/21.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "libControlScrollView.h"

@implementation libScrollView
//--------------------------------------------------------------------
// タッチ開始時
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	[[self superview] touchesBegan:touches withEvent:event];
}
//--------------------------------------------------------------------
// タッチ終了時
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	[[self superview] touchesEnded:touches withEvent:event];
}
@end

@interface libControlScrollView(private)
- (void)setAutoView:(u_int)page;
- (void)setScroll:(u_int)page animated:(BOOL)animated;
- (void)changePage;
@end

@implementation libControlScrollView
@synthesize m_AutoViewList;
@synthesize m_btnMoveLeft;
@synthesize m_btnMoveRight;

//--------------------------------------------------------------------
// 初期化
- (id)initWithFrame:(CGRect)frame {
    return [self initWithFrame:frame width:frame.size.width];
}
- (id)initWithFrame:(CGRect)frame width:(CGFloat)width{
    if (self = [super initWithFrame:frame]) {
        // Initialization code
		self.clipsToBounds = YES;

		// スクロールビュー設定
		m_ScrollView = [[libScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
		m_ScrollView.pagingEnabled = NO;
		m_ScrollView.showsHorizontalScrollIndicator = NO;
		m_ScrollView.showsVerticalScrollIndicator = NO;
		m_ScrollView.delegate = self;
		[self addSubview:m_ScrollView];
		
		// ページコントロール表示設定
		m_PageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, frame.size.height-18, frame.size.width, 18)];
		[m_PageControl addTarget:self action:@selector(changePage) forControlEvents:UIControlEventTouchUpInside];
		[self addSubview:m_PageControl];
		m_numberOfPages = 0;
		
		// メンバ初期化
		m_width = width;
		m_AutoViewList = nil;
		m_auto_move_time = 0;
		
		// Move buttons
		m_btnMoveLeft = nil;
		m_btnMoveRight = nil;
		
		// オートサイズ設定
		[self setAutoresizingMaskAll:VIEW_AUTORESIZE_ALL];
    }
    return self;
}

//--------------------------------------------------------------------
// 解放
- (void)dealloc {
	m_ScrollView.delegate = nil;
	SAFE_RELEASE(m_ScrollView);
	SAFE_RELEASE(m_PageControl);
	SAFE_RELEASE(m_AutoViewList);
    [super dealloc];
}

//--------------------------------------------------------------------
// 解放
- (void)update
{
	[self update:CS_AUTO_MOVE_TIME_NORMAL];
}
- (void)update:(double)time
{
	// 自動切り替え処理
	if( m_auto_move_time && m_PageControl.numberOfPages > 1 )
	{
		double nowTime = CFAbsoluteTimeGetCurrent();
		if( (nowTime - m_auto_move_time ) >= time )
		{
			m_auto_move_time = nowTime;
			[self setScroll:2 animated:YES];
		}
	}
	
	[super update];
}

//--------------------------------------------------------------------
// オートサイズ設定
- (void)setAutoresizingMaskAll:(UIViewAutoresizing)autoresizingMask
{
	self.autoresizingMask = autoresizingMask;
	if( m_ScrollView )
	{
		m_ScrollView.autoresizingMask = autoresizingMask;
	}
	if( m_PageControl )
	{
		m_PageControl.autoresizingMask = autoresizingMask;
	}
}

//--------------------------------------------------------------------
// ページコントロール表示設定
- (void)setPageControlHidden:(BOOL)hidden
{
	m_PageControl.hidden = hidden;
}

//--------------------------------------------------------------------
// View追加
- (void)addView:(ViewBase*)view
{
	CGFloat difference = (m_ScrollView.frame.size.width - m_width);
	CGRect frame = view.frame;
	frame.origin.x = m_width * m_numberOfPages + (m_width - view.frame.size.width) / 2 + difference / 2;
/*
	CGFloat height = m_ScrollView.frame.size.height;
	if(height - view.frame.size.height > m_PageControl.frame.size.height)
	{
		height -= m_PageControl.frame.size.height;
	}
	frame.origin.y = (height - view.frame.size.height) / 2;
*/
	view.frame = frame;
	[m_ScrollView addSubview:view];
	
	// ページカウント加算
	if( !m_AutoViewList )
	{
		m_PageControl.numberOfPages++;
	}
	m_numberOfPages++;
	// スクロール範囲再設定
	m_ScrollView.contentSize = CGSizeMake(m_width * m_numberOfPages + difference, m_ScrollView.frame.size.height);
}

//--------------------------------------------------------------------
// View削除
- (BOOL)removeView:(ViewBase*)view
{
	for( ViewBase* view_ in [m_ScrollView subviews] )
	{
		if( view_ == view )
		{
			[view removeFromSuperview];
			CGFloat difference = (m_ScrollView.frame.size.width - m_width);
			if( !m_AutoViewList )
			{
				m_PageControl.numberOfPages--;
			}
			m_numberOfPages--;
			m_ScrollView.contentSize = CGSizeMake(m_width * m_numberOfPages + difference, m_ScrollView.frame.size.height);
			return YES;
		}
	}
	return NO;
}
// ページ指定
- (BOOL)removeViewWithNo:(u_int)page
{
	if( [[m_ScrollView subviews] count] > page )
	{
		ViewBase* view = [[m_ScrollView subviews] objectAtIndex:page];
		[view removeFromSuperview];
		CGFloat difference = (m_ScrollView.frame.size.width - m_width);
		if( !m_AutoViewList )
		{
			m_PageControl.numberOfPages--;
		}
		m_numberOfPages--;
		m_ScrollView.contentSize = CGSizeMake(m_width * m_numberOfPages + difference, m_ScrollView.frame.size.height);
		return YES;
	}
	return NO;
}
// 全部削除
- (void)removeAllView
{
	for( ViewBase* view in [m_ScrollView subviews] )
	{
		[view removeFromSuperview];
	}
	if( !m_AutoViewList )
	{
		m_PageControl.numberOfPages = 0;
	}
	m_numberOfPages = 0;
	m_ScrollView.contentSize = m_ScrollView.frame.size;
}

//--------------------------------------------------------------------
// オート移動ViewList設定
- (void)setAutoViewList:(NSArray*)list
{
	[self setAutoViewList:list num:0];
}
- (void)setAutoViewList:(NSArray*)list num:(u_int)num
{
	// ３画面以上必要
	if( [list count] < CS_AUTO_VIEW_NUM )
	{
		return;
	}

	SAFE_RELEASE(m_AutoViewList);
	m_AutoViewList = [list retain];
	m_auto_page_no = 0;
	m_auto_move_time = CFAbsoluteTimeGetCurrent();
	m_PageControl.numberOfPages = num? num : [list count];
	m_PageControl.currentPage = 0;
	[self setAutoView:0];
	
	// センター表示
	[self setScroll:1 animated:NO];
	// ページコントロールは非表示
//	[self setPageControlHidden:YES];
}

//--------------------------------------------------------------------
// オート移動View設定
- (void)setAutoView:(u_int)page
{
	[self removeAllView];
	[self addView:[m_AutoViewList objectAtIndex:(page != 0)? page-1 : [m_AutoViewList count]-1]];
	[self addView:[m_AutoViewList objectAtIndex:page]];
	[self addView:[m_AutoViewList objectAtIndex:(page != [m_AutoViewList count]-1)? page+1 : 0]];
}

//--------------------------------------------------------------------
// 表示中のページ番号取得
- (u_int)getCurrentPage
{
	return m_PageControl.currentPage;
}

//--------------------------------------------------------------------
// 指定したページ表示
- (BOOL)setCurrentPage:(u_int)pege_no
{
	if( m_PageControl.numberOfPages <= pege_no )
	{
		return NO;
	}
	if( m_AutoViewList )
	{
		m_auto_page_no = pege_no;
		[self setAutoView:pege_no];
		[self setScroll:1 animated:NO];
	}
	else
	{
		[self setScroll:pege_no animated:NO];
	}
	[self scrollViewDidEndScrollingAnimation:m_ScrollView];
	return YES;
}

//--------------------------------------------------------------------
// 前のページへ
- (void)toPrevPage
{
	if( m_AutoViewList )
	{
		[self setScroll:0 animated:YES];
	}
	else
	{
		int page = [m_PageControl currentPage];
		if( page )
		{
			page--;
		}
		[self setScroll:page animated:YES];
	}
}

//--------------------------------------------------------------------
// 次のページへ
- (void)toNextPage
{
	if( m_AutoViewList )
	{
		[self setScroll:2 animated:YES];
	}
	else
	{
		int page = [m_PageControl currentPage];
		int maxPage = [m_PageControl numberOfPages];
		if( ++page > maxPage )
		{
			page = maxPage;
		}
		[self setScroll:page animated:YES];
	}
}

//-------------------------------------------------------------------
// 回転開始時の処理
- (void)willRotate:(UIInterfaceOrientation)orie duration:(NSTimeInterval)duration
{
	m_rotate_ratio = m_width / self.frame.size.width;
	
	[super willRotate:orie duration:duration];
}

//-------------------------------------------------------------------
// 回転終了時の処理
- (void)didRotate:(UIInterfaceOrientation)orie
{
	m_width = self.frame.size.width * m_rotate_ratio;
	CGFloat difference = (m_ScrollView.frame.size.width - m_width);
	m_ScrollView.contentSize = CGSizeMake(m_width * m_numberOfPages + difference, m_ScrollView.frame.size.height);
	
	[super didRotate:orie];
}

//--------------------------------------------------------------------
// スクロール設定
- (void)setScroll:(u_int)page animated:(BOOL)animated
{
	// オート移動設定の場合はView再配置
	if( m_AutoViewList )
	{
		if( page != 1 )
		{
			CGPoint offset = m_ScrollView.contentOffset;
			if( page > 1 )
			{
				if( m_auto_page_no < [m_AutoViewList count]-1 )
				{
					m_auto_page_no++;
				}
				else
				{
					m_auto_page_no = 0;
				}
				offset.x -= m_width;
			}
			else
			{
				if( m_auto_page_no > 0 )
				{
					m_auto_page_no--;
				}
				else
				{
					m_auto_page_no = [m_AutoViewList count]-1;
				}
				offset.x += m_width;
			}
			
			[self setAutoView:m_auto_page_no];
			m_ScrollView.contentOffset = offset;
			page = 1;
		}
	}
	// 任意の位置にスクロール
	CGRect frame = m_ScrollView.frame;
	frame.origin.x = m_width * page;
	[m_ScrollView scrollRectToVisible:frame animated:animated];
	
	if( !m_AutoViewList && animated == NO )
	{
		m_PageControl.currentPage = page;
	}
	
	// Moving buttons
	if (m_btnMoveLeft)	m_btnMoveLeft.hidden = page == 0;
    if (m_btnMoveRight) m_btnMoveRight.hidden = (page == [m_PageControl numberOfPages] - 1);
	
}

//--------------------------------------------------------------------
// UIPageControlがタップされた時
- (void)changePage
{
	if( m_AutoViewList )
	{
		u_int page = 1 + (m_PageControl.currentPage - m_auto_page_no);
		[self setScroll:page animated:YES];
	}
	else
	{
		[self setScroll:m_PageControl.currentPage animated:YES];
	}
}

//--------------------------------------------------------------------
// スクロールアニメーション終了
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{  
	// オート移動はタイマーをリセットする
	if( m_AutoViewList )
	{
		m_auto_move_time = CFAbsoluteTimeGetCurrent();
		m_PageControl.currentPage = m_auto_page_no;
	}
	else
	{
		// PageControl調整
		m_PageControl.currentPage = scrollView.contentOffset.x / m_width;
	}
}

//--------------------------------------------------------------------
// スクロール開始
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	// オート移動を中断
	m_auto_move_time = 0;
}

//--------------------------------------------------------------------
// スライド終了時
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{ 
	if( (scrollView.contentOffset.x < 0 || scrollView.contentOffset.x > m_width * (m_numberOfPages - 1)) && !m_AutoViewList )
	{
		[self scrollViewDidEndScrollingAnimation:scrollView];
		
		// Moving buttons
		if (m_btnMoveLeft) m_btnMoveLeft.hidden = m_PageControl.currentPage == 0;
		if (m_btnMoveRight) m_btnMoveRight.hidden = (m_PageControl.currentPage == [m_PageControl numberOfPages] - 1);
		
		return;
	}
	
	if( !decelerate )
	{
		u_int page = (scrollView.contentOffset.x + m_width / 2) / m_width;
		// スクロール
		[self setScroll:page animated:YES];
	}
}

//--------------------------------------------------------------------
// 減速開始時
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{ 
	if( (scrollView.contentOffset.x < 0 || scrollView.contentOffset.x > m_width * (m_numberOfPages - 1)) && !m_AutoViewList )
	{
		return;
	}
	
	// 動いたらページ変更
	u_int base_page = m_PageControl.currentPage;
	if( m_AutoViewList )
	{
		base_page = 1;
	}
	int page = base_page;
	CGFloat offset = m_width * base_page;
	if( scrollView.contentOffset.x > offset )
	{
		page++;
	}
	else if( scrollView.contentOffset.x < offset )
	{
		page--;
	}
	if( page < 0 || page >= m_numberOfPages )
	{
		page = base_page;
	}
	// スクロール
	[self setScroll:page animated:YES];
}

//--------------------------------------------------------------------
// タッチ開始時
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	// オート移動を中断
	m_auto_move_time = 0;
}

//--------------------------------------------------------------------
// タッチ終了時
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	if( (m_ScrollView.contentOffset.x < 0 || m_ScrollView.contentOffset.x > m_width * (m_numberOfPages - 1)) && !m_AutoViewList )
	{
		[self scrollViewDidEndScrollingAnimation:m_ScrollView];
		return;
	}
	
	u_int page = (m_ScrollView.contentOffset.x + m_width / 2) / m_width;
	// スクロール
	[self setScroll:page animated:YES];
	
	// オート移動はタイマーをリセットする
	if( m_AutoViewList )
	{
		m_auto_move_time = CFAbsoluteTimeGetCurrent();
	}
}

//--------------------------------------------------------------------
// ページコントロールの座標を変更
- (void)setPageControlPos:(int)offsetY
{
	m_PageControl.frame = CGRectMake( m_PageControl.frame.origin.x, self.frame.origin.y + offsetY, m_PageControl.frame.size.width, m_PageControl.frame.size.height );
}

//--------------------------------------------------------------------
// ドラッグを無効にする
- (void)disableDrag
{
	m_ScrollView.scrollEnabled = FALSE;
}

//--------------------------------------------------------------------
// ページコントロールの操作を無効にする
- (void)disablePageControllInteraction
{
	m_PageControl.userInteractionEnabled = FALSE;
}

//--------------------------------------------------------------------
// ページコントロールを削除
- (void)removePageControl
{
	[m_PageControl removeFromSuperview];
}

//Toanh begin
- (void) setAutoScroll: (BOOL) isAutoScroll
{
	[m_ScrollView setScrollEnabled:isAutoScroll]; 
}
- (int) getMaxNumber
{
	return [m_PageControl numberOfPages];
}

@end
